// @ts-check
class Event {

  constructor() {
    /** @type {import('../types').ListenerMap} */
    this.listenerMap = {}
  }
  /**
     * 添加监听器
     * @param {import('../types').EventTypes} eventType
     * @param {import('../types').ListenerFn} listener
    */
  addListener(eventType, listener) {
    if(eventType) {
      if(this.listenerMap[eventType]) {
        let index = this.listenerMap[eventType].findIndex(i => i == listener)
        if(index < 0) {
          this.listenerMap[eventType].push(listener)
        }else {
          this.listenerMap[eventType][index] = listener
        }
      }else {
        this.listenerMap[eventType] = [listener]
      }
    }
  }
  /**
     * 添加监听器
     * @param {import('../types').EventTypes} eventType
     * @param {import('../types').ListenerFn} listener
    */
  removeListener(eventType = undefined, listener = undefined) {
    if(eventType) {
      if(!listener) {
        this.listenerMap[eventType] = []
      }else {
        if(this.listenerMap[eventType]) {
          this.listenerMap[eventType] = this.listenerMap[eventType].filter(i => i != listener)
        }
      }
    }else {
      for(let key in this.listenerMap) {
        this.listenerMap[key] = []
      }
    }
  }

  /**
   * 触发事件
   * @param {import('../types').EventTypes} eventType
   */
  triggerEvent(eventType) {
    this.listenerMap[eventType]  && this.listenerMap[eventType].forEach(i => i && i())
  }

}

export default new Event()
